//
//  PublishCommentViewController.m
//  YunGou
//
//  Created by macbook on 16/5/19.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "PublishCommentViewController.h"
#import "AddPhotoView.h"
#import "CustomTextView.h"
#import "NSObject+Tools.h"

@interface PublishCommentViewController ()
@property (weak, nonatomic) IBOutlet AddPhotoView *addPhotoView;
@property (weak, nonatomic) IBOutlet CustomTextView *commentText;
@property (nonatomic,strong) UIImageView *selectedImage;
@end

@implementation PublishCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _commentText.placeholder = @"请发表获奖感言，让别人羡慕一下吧";
    
    _addPhotoView.imageTapBlock = ^(UIImageView *image){
        _selectedImage = image;
        [self addPhoto:_selectedImage];
    };
    
    //点击删除按钮删除图片
    _addPhotoView.deleteImageBlock = ^(UIButton *btn){
        UIImageView *deleteImg = [btn getAccessoryObject];
        UIImage *img = deleteImg.image;
        [_addPhotoView.imageArray removeObject:img];
        [deleteImg removeFromSuperview];
    };
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyBoard)];
    [self.view addGestureRecognizer:tap];
}

- (void)hiddenKeyBoard{
    [self.view endEditing:YES];
}

- (void)addPhoto:(UIImageView *)image{
    UIAlertController *alerVc = [UIAlertController alertControllerWithTitle:@"选择您的照片" message:@"您可以从相机拍摄照片或者从相册中选择" preferredStyle:UIAlertControllerStyleActionSheet];
    __weak __typeof(self)weakSelf = self;
    UIAlertAction *actionCamera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf pickImageBySourceType:UIImagePickerControllerSourceTypeCamera];
    }];
    
    UIAlertAction *actionImagePicker = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf pickImageBySourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    [alerVc addAction:actionCamera];
    [alerVc addAction:actionImagePicker];
    [alerVc addAction:actionCancel];
    [self presentViewController:alerVc animated:YES completion:nil];
    
}

- (void)pickImageBySourceType:(UIImagePickerControllerSourceType)sourceType
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = YES;
    picker.delegate   = (id)self;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //退出选择器
    [self dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = (UIImage *)info[@"UIImagePickerControllerOriginalImage"];
    
    if (_addPhotoView.imageArray.count != 4) {
        if (_selectedImage.tag == 0) {
            [self.addPhotoView addImage:image];
        }else{
            [self.addPhotoView.imageArray replaceObjectAtIndex:_selectedImage.tag withObject:image];
            [self.addPhotoView layoutSubviews];
        }
    }else{
        [self.addPhotoView.imageArray replaceObjectAtIndex:_selectedImage.tag withObject:image];
        [self.addPhotoView layoutSubviews];
    }
}

- (IBAction)showOrderClicked:(UIButton *)sender {
    if (_commentText.text.length == 0) {
        [MBProgressHUD showError:@"内容不能为空"];
    }else{
        if (self.addPhotoView.imageArray.count == 1) {
            [MBProgressHUD showError:@"图片不能为空"];
        }else{
            NSMutableArray *pathArray = [NSMutableArray array];
            [MBProgressHUD showMessage:@"正在发表"];
            for (NSInteger i = 1; i < self.addPhotoView.imageArray.count; i ++) {
                @synchronized(self) {
                    [NetWorkTool uploadWithImage:self.addPhotoView.imageArray[i] success:^(id object) {
                        NSMutableString *path = [NSMutableString stringWithString:object[@"path"]];
                        [pathArray addObject:[path substringFromIndex:18]];
                        
                        if (i == self.addPhotoView.imageArray.count - 1 && pathArray.count == self.addPhotoView.imageArray.count - 1) {
                            NSString *paths = [pathArray componentsJoinedByString:@","];
                            
                            [NetWorkTool addShareOrderWithGoodsId:_winRecordModel.Id sd_issue:_winRecordModel.qishu sd_ip:nil sd_title:nil sd_content:_commentText.text sd_photoList:paths success:^(id object) {
                                [MBProgressHUD hideHUD];
                                if ([object[@"code"] integerValue] == 1) {
                                    [MBProgressHUD showSuccess:@"晒单成功"];
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 *  NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        [self.navigationController popViewControllerAnimated:YES];
                                    });
                                }else{
                                    [MBProgressHUD showError:@"晒单失败"];
                                }
                            } failure:^(NSError *error) {
                                FZLog(@"%@",error);
                            }];
                            
                        }
                    } failure:^(NSError *error) {
                        FZLog(@"%@",error);
                    }];

                }
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
